package com.cys.markdown.doc.admin.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * MyBatis 配置文件
 * Created by caiyushen on 2018/12/23.
 */
@Configurable
@MapperScan(basePackages = {"com.cys.markdown.doc.*.interfaces.dao", "com.cys.mid.core.**.interfaces.dao"}, sqlSessionTemplateRef = "sqlSessionTemplate")
public class MyBatisConfig {

    private Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);

    @Value("${spring.druid.account}")
    private String loginUsername;

    @Value("${spring.druid.pwd}")
    private String loginPassword;

    //Spring boot dataSource 数据源
//    @Bean(name = "dataSource")
//    @Primary
//    @ConfigurationProperties(prefix = "spring.datasource.main")
//    public DataSource dataSource() {
//        return DataSourceBuilder.create().build();
//    }

    // 阿里巴巴德鲁伊数据源
    @Bean("dataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @Primary
    public DruidDataSource dataSource() {
        return new DruidDataSource();
    }

    /**
     * 阿里德鲁伊监控页面配置
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        registrationBean.addInitParameter("allow", "");// IP白名单 (没有配置或者为空，则允许所有访问)
        registrationBean.addInitParameter("deny", "");// IP黑名单 (存在共同时，deny优先于allow)
        //http://localhost:8088/druid/sql.html
        registrationBean.addInitParameter("loginUsername", loginUsername);
        registrationBean.addInitParameter("loginPassword", loginPassword);
        registrationBean.addInitParameter("resetEnable", "false");
        return registrationBean;
    }


    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath*:mapper/*/*_Mapper.xml"));
            bean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
            return bean.getObject();
        } catch (Exception e) {
            logger.error("method[sqlSessionFactory] e:" + e.toString());
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory); // 使用上面配置的Factory
        return template;
    }

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * MyBatis 热加载
     */
    @Bean
    public MybatisMapperDynamicLoader mybatisMapperDynamicLoader() {
        return new MybatisMapperDynamicLoader();
    }

    /**
     * 引入pageHelper的MyBatis拦截器插件
     */
    @Bean
    public PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        //配置数据源为mysql
        properties.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }


}
